import React, {PropsWithChildren, useEffect, useMemo, useState} from 'react'
import {Text, View} from "@tarojs/components";
import {
    Button,
    Cell,
    Col,
    Form,
    FormItem,
    Input,
    InputNumber,
    Row,
    Space,
    TextArea
} from "@nutui/nutui-react-taro";
import {AddGoodsRequest} from "../apis/GoodsApi";
import {NumberIdAndName} from "../types/BasicModels";
import {getAllGoodsBrand, GoodsBrandSummary} from "../apis/GoodsBrandsApi";
import SingleSelectableListActionSheet from "./SingleSelectableListActionSheet";
import {getAllGoodsCategories} from "../apis/GoodsCategoriesApi";
import {Plus} from "@nutui/icons-react-taro";
import ArrayUtils from "@zxy-cn/array-utils";
import Taro from "@tarojs/taro";

export interface GoodsEditFormData {
    name: string
    barcode: string
    price: number
    amount: number
    brand?: NumberIdAndName
    category?: NumberIdAndName
    units: EditGoodsUnitData[]
}

export interface GoodsEditInitialValue {
    name: string
    barcode: string
    price: number
    amount: number
    brandId?: AddGoodsRequest["brandId"]
    categoryId?: AddGoodsRequest["categoryId"]
    units: EditGoodsUnitData[]
    registrationCertificateNumber?:string,
    recordFilingNumber?:string,
    executiveStandard?:string,
    note?:string
    boxSpecification?: string
}

interface EditGoodsUnitData {
    id?: number
    name: string
    basicMultiple: number
    updatable: boolean
    registrationCertificateNumber?:string,
    recordFilingNumber?:string,
    executiveStandard?:string,
    note?:string
}


export interface GoodsEditFormProps extends PropsWithChildren {
    initialValue?: GoodsEditInitialValue
    onConfirm: (value: GoodsEditInitialValue, data: GoodsEditFormData) => Promise<void>
}

const GoodsEditForm: React.FC<GoodsEditFormProps> = ({initialValue, onConfirm}) => {
    const [confirming, setConfirming] = useState(false)
    const [goodsUnitList, setGoodsUnitList] = useState(initialValue?.units ?? [])

    const [brands, setBrands] = useState<GoodsBrandSummary[]>([])
    useEffect(() => {
        getAllGoodsBrand().then(response => {
            setBrands(response.data)
        })
    }, []);
    const [selectedBrandId, setSelectedBrandId] = useState(initialValue?.brandId)
    const [showSelectBrandPopup, setShowSelectBrandPopup] = useState(false)

    const [categories, setCategories] = useState<NumberIdAndName[]>([])
    useEffect(() => {
        getAllGoodsCategories().then(response => {
            setCategories(response.data)
        })
    }, []);
    const [selectedCategoryId, setSelectedCategoryId] = useState(initialValue?.categoryId)
    const [showSelectGoodsCategoryPopup, setShowSelectGoodsCategoryPopup] = useState(false)

    const selectedBrand = useMemo(() => {
        return brands.find(it => it.id === selectedBrandId)
    }, [selectedBrandId,brands]);

    const selectedCategory = useMemo(() => {
        return categories.find(it => it.id === selectedCategoryId)
    }, [selectedCategoryId,categories]);
    return <>
        <Form footer={<Button formType={"submit"} type={"primary"}
                              loading={confirming} block>保存</Button>}
              labelPosition={"top"} initialValues={initialValue} onFinish={async (values) => {
            console.log("confirm", values)
            setConfirming(true)
            try {
                await onConfirm({
                    ...values,
                    brandId: selectedBrandId,
                    units: goodsUnitList,
                    categoryId: selectedCategoryId,
                }, {
                    name: values.name,
                    barcode: values.barcode,
                    price: values.price,
                    amount: values.amount,
                    units: goodsUnitList,
                    brand: selectedBrand,
                    category: selectedCategory,
                })
                Taro.navigateBack()
            } finally {
                setConfirming(false)
            }
        }}>
            <Form.Item required label={"名称"} name={"name"}
                       rules={[{required: true, message: "请输入货品名称"}]}>
                <Input placeholder={"名称"}/>
            </Form.Item>
            <Form.Item required label={"条码"} name={"barcode"}
                       rules={[{required: true, message: "请输入货品条码"}]}>
                <Input placeholder={"条码"} type={"number"}/>
            </Form.Item>
            <Row gutter={8}>
                <Col span={12}>
                    <Form.Item required label={"零售价"} name={"price"}
                               rules={[{required: true, message: "请输入货品零售价"}]}>
                        <Input placeholder={"零售价"} type={"digit"}/>
                    </Form.Item>
                </Col>
                <Col span={12}>
                    <Form.Item label={"库存"} name={"amount"}>
                        <InputNumber min={0} value={initialValue?.amount ?? 0}/>
                    </Form.Item>
                </Col>
            </Row>
            <Form.Item label={"箱规"} name={"boxSpecification"}>
                <Input placeholder={"箱规"} type={"text"}/>
            </Form.Item>
            <Form.Item label={"品牌"} name={"brandId"}>
                <Cell title={selectedBrand?.name ?? "选择品牌"}
                      onClick={() => {
                          setShowSelectBrandPopup(true)
                      }}
                />
            </Form.Item>
            <Form.Item label={"类别"} name={"categoryId"}>
                <Cell title={selectedCategory?.name ?? "选择类别"}
                      onClick={() => {
                          setShowSelectGoodsCategoryPopup(true)
                      }}
                />
            </Form.Item>
            <GoodsUnitEditFormItem value={goodsUnitList} onChange={setGoodsUnitList}/>
            <Form.Item label={"生产证编号"} name={"registrationCertificateNumber"}
                       rules={[{max: 50}]}
            >
                <Input placeholder={"输入名称"}/>
            </Form.Item>
            <Form.Item label={"备案编号"} name={"recordFilingNumber"}
                       rules={[{max: 50}]}
            >
                <Input placeholder={"输入备案编号"}/>
            </Form.Item>
            <Form.Item label={"执行标准"} name={"executiveStandard"}
                       rules={[{max: 50}]}
            >
                <Input placeholder={"输入执行标准"}/>
            </Form.Item>
            <Form.Item label={"备注"} name={"note"}>
                <TextArea placeholder={"输入备注"}/>
            </Form.Item>
        </Form>
        <SingleSelectableListActionSheet value={selectedBrandId} visible={showSelectBrandPopup}
                                         onCancel={() => setShowSelectBrandPopup(false)}
                                         onChange={value => {
                                             setSelectedBrandId(value)
                                         }}
                                         options={brands.map(it => ({key: it.id, label: it.name,}))}/>

        <SingleSelectableListActionSheet value={selectedCategoryId} visible={showSelectGoodsCategoryPopup}
                                         onCancel={() => setShowSelectGoodsCategoryPopup(false)}
                                         onChange={(values) => {
                                             setSelectedCategoryId(values)
                                         }}
                                         options={categories.map(it => ({key: it.id, label: it.name}))}/>


    </>
}
export default GoodsEditForm

interface GoodsUnitEditFormItemProps {
    value: EditGoodsUnitData[]
    onChange: (value: EditGoodsUnitData[]) => void
}

const GoodsUnitEditFormItem: React.FC<GoodsUnitEditFormItemProps> = ({value, onChange}) => {
    const basicUnit = useMemo(() => {
        return value.find(it => it.basicMultiple === 0)?.name
    }, [value]);
    console.log(basicUnit,value)
    return <>
        <Cell title={"单位"} description={<Input style={{paddingLeft:0}} placeholder={"输入主单位"} value={basicUnit} onChange={(v) => {
            const list = Array.from(value)
            let item = list.find(it => it.basicMultiple === 0);
            if (item) {
                item.name = v
                onChange(list)
            }
        }}/>}/>
        {value.length > 1 && value.filter(it=>it.basicMultiple!==0).map((unit, index) => {
            return <FormItem label={`辅助单位${index + 1}`}>
                <Space key={unit.id} align={"center"}>
                    <Input style={{width: 64}} type={"text"} value={unit.name} onChange={(v) => {
                        let item = value.find(it => it === unit);
                        if (item) {
                            item.name = v
                            onChange(Array.from(value))
                        }
                    }}/>
                    <Plus/>
                    <InputNumber min={1} value={unit.basicMultiple} onChange={v => {
                        let item = value.find(it => it === unit);
                        if (item) {
                            item.basicMultiple = Number(v) || 1
                            onChange(Array.from(value))
                        }
                    }}/>
                    <Text>{basicUnit}</Text>
                    <View style={{height: 1, flexGrow: 1}}/>
                    <Button size={"small"} fill={"outline"} onClick={() => {
                        if (ArrayUtils.remove(value, unit))
                            onChange(Array.from(value))
                    }}>删除</Button>
                </Space>
            </FormItem>
        })}
        <View style={{padding: "0 12px"}}>
            <Button block type={"primary"} fill={"dashed"} onClick={() => {
                onChange(Array.from(value).concat([{basicMultiple: 1, name: "", updatable: true}]))
            }}>添加辅助单位</Button>
        </View>
    </>
}